package com.punch.oauth.openid;

import com.punch.common.model.LoginUser;
import com.punch.oauth.service.impl.UaaUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;

/**
 * @author mall
 */
public class OpenIdAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UaaUserServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
        String openId = (String) authenticationToken.getPrincipal();
        int type = authenticationToken.getType();

        LoginUser user = userDetailsService.loadUserByOpenId(openId, type);
        OpenIdAuthenticationToken authenticationResult = new OpenIdAuthenticationToken(user, type, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UaaUserServiceImpl getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UaaUserServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
